<template>
  <div>
    <div>
      <el-config-provider :locale="zhCn">
        <el-scrollbar height="70vh">
          <!-- 请假申请 -->
          <el-row :gutter="24">
            <el-col :span="24">
              <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                <el-form-item label="请假申请" label-position="top"
                  :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                  <div class="progress-bar">
                    <div class="progress"></div>
                  </div>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="12">
              <!-- {{ vacationBalanceData }} -->
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="调休单号" label-position="top">
                  <el-input placeholder="自动生成无需填写" style="width: 354px;" disabled />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <!-- {{ vacationData }} -->
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="申请日期" label-position="top">
                  <el-input :value="formData.applicationDate" style="/*width: 260px;*/" disabled />
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="请假类型" label-position="top">
                  <el-input placeholder="调休" style="/*width: 260px;*/" disabled />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="姓名" label-position="top">
                  <el-input :value="user.employeeName" style="/*width: 354px;*/" disabled />
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="所在部门" label-position="top">
                  <el-input :value="user.department.deptName" style="/*width: 260px;*/" disabled />
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="24">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="调休" label-position="top" required>
                  <span style="font-size: 12px;">若调休多日，请按照时段逐一填写。</span>

                  <el-table :data="vacationData" border stripe>
                    <el-table-column type="index" width="50" />
                    <el-table-column prop="leaveDate" label="请假日期" width="160">
                      <template #default="scope">
                        <el-date-picker v-model="scope.row.leaveDate" type="date" value-format="YYYY-MM-DD"
                          placeholder="选择日期" style="width: 100%" @change="calculateLeaveInfo(scope.$index)"
                          :disabled-date="disabledDate" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="leavePeriod" label="请假时段" width="160">
                      <template #default="scope">
                        <el-select v-model="scope.row.leavePeriod" placeholder="请选择时段" style="width: 100%"
                          @change="calculateLeaveInfo(scope.$index)">
                          <el-option label="上午" value="上午" />
                          <el-option label="下午" value="下午" />
                          <el-option label="全天" value="全天" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="leaveDays" label="请假天数小计" width="160">
                      <template #default="scope">
                        <el-input v-model="scope.row.leaveDays" disabled style="width: 100%" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="attendancePeriod" label="归属考勤周期" width="200">
                      <template #default="scope">
                        <el-input v-model="scope.row.attendancePeriod" disabled style="width: 100%" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                      <template #default="scope">
                        <el-button size="small" type="danger" @click="removeRow(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>

                <div class="action-btns" style="margin-top: 12px">
                  <el-button type="primary" icon="Plus" @click="addRow">
                    添加
                  </el-button>
                </div>
              </div>
            </el-col>

            <el-col :span="24">
              <!-- 空白分隔区域 -->
              <div style="height: 10px; border-top: 0px dashed #e4e7ed; margin: 6px 0;"></div>
            </el-col>

            <el-col :span="12">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="合计调休天数" label-position="top" required>
                  <el-input v-model="totalLeaveDays" placeholder="" style="width: 354px;" disabled />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="可用调休天数" label-position="top">
                  <el-input v-model="vacationBalanceData.vacationDays" placeholder="" style="/*width: 260px;*/"
                    disabled />
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="调休完可用天数" label-position="top" required>
                  <el-input v-model="remainingDays" placeholder="0" style="/*width: 354px;*/" disabled />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content ep-bg-purple-light">
                <el-form-item label="调休事由说明" label-position="top">
                  <el-input v-model="textarea" style="width: 633px;" :rows="6" type="textarea" placeholder="" />
                </el-form-item>
              </div>
            </el-col>

            <div class="bottom-submit-bar">
              <el-button type="primary" @click="submitVacationApplication">提交</el-button>
            </div>
          </el-row>
        </el-scrollbar>
      </el-config-provider>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, defineEmits } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router';
import request from '@/api/request';

let emits = defineEmits(['ref-table']);

// 获取session中的用户信息
const user = JSON.parse(sessionStorage.getItem('user') || '{}');

const textarea = ref('')
const totalLeaveDays = ref('')
const remainingDays = ref('')

const formData = ref({})

const vacationBalanceData = ref({
  vacationDays: 0
});

let loadVacationBalance = () => {
  request({
    url: '/vacationBalance/list'
  }).then(resp => {
    vacationBalanceData.value = resp.data
  })
}

const disabledDate = (time) => {
  // 禁用今天之前的日期（不包括今天）
  return time.getTime() < new Date(new Date().setHours(0, 0, 0, 0));
};

// 调休明细数据源
const vacationData = ref([{
  leaveDate: '',
  leavePeriod: '',
  leaveDays: '',
  attendancePeriod: ''
}])

// 添加新的调休记录
const addRow = () => {
  vacationData.value.push({
    leaveDate: '',
    leavePeriod: '',
    leaveDays: '',
    attendancePeriod: ''
  })
}

// 删除指定的调休记录
const removeRow = (index) => {
  if (vacationData.value.length <= 1) {
    ElMessage.warning('至少需要保留一条调休记录')
    return
  }
  vacationData.value.splice(index, 1)
  calculateTotalLeaveDays()
}

// 计算单条调休记录的信息
const calculateLeaveInfo = (index) => {
  const row = vacationData.value[index]

  // 验证必填项
  if (!row.leaveDate || !row.leavePeriod) {
    row.leaveDays = ''
    row.attendancePeriod = ''
    return
  }

  // 计算请假天数
  switch (row.leavePeriod) {
    case '上午':
    case '下午':
      row.leaveDays = '0.5'
      break
    case '全天':
      row.leaveDays = '1.0'
      break
    default:
      row.leaveDays = '0.0'
  }

  // 计算归属考勤周期
  const date = new Date(row.leaveDate)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  row.attendancePeriod = `${year}-${month}`
}

// 计算总调休天数
const calculateTotalLeaveDays = () => {
  let total = 0
  vacationData.value.forEach(row => {
    if (row.leaveDays && !isNaN(parseFloat(row.leaveDays))) {
      total += parseFloat(row.leaveDays)
    }
  })
  totalLeaveDays.value = total.toFixed(1)
  calculateRemainingDays()
}

// 计算调休后剩余天数
const calculateRemainingDays = () => {
  const available = parseFloat(vacationBalanceData.value.vacationDays) || 0
  const total = parseFloat(totalLeaveDays.value) || 0
  remainingDays.value = (available - total).toFixed(2)
}

// 提交调休申请
const submitVacationApplication = () => {
  // 验证必填项
  if (vacationData.value.length === 0) {
    ElMessage.warning('请至少添加一条调休记录')
    return
  }

  // 验证每条调休记录
  for (let i = 0; i < vacationData.value.length; i++) {
    const row = vacationData.value[i]
    if (!row.leaveDate) {
      ElMessage.warning(`第${i + 1}条调休记录缺少请假日期`)
      return
    }
    if (!row.leavePeriod) {
      ElMessage.warning(`第${i + 1}条调休记录缺少请假时段`)
      return
    }
  }

  // 检测重复的请假日期
  const dateSet = new Set()
  const duplicateDates = []

  vacationData.value.forEach((row, index) => {
    if (dateSet.has(row.leaveDate)) {
      // 检查是否已记录该重复日期
      if (!duplicateDates.includes(row.leaveDate)) {
        duplicateDates.push(row.leaveDate)
      }
    } else {
      dateSet.add(row.leaveDate)
    }
  })

  if (duplicateDates.length > 0) {
    ElMessage.warning(`以下日期存在重复记录: ${duplicateDates.join(', ')}`)
    return
  }

  if (!textarea.value) {
    ElMessage.warning('请输入调休事由说明')
    return
  }

  // 检查调休后天数是否为负数
  const available = parseFloat(vacationBalanceData.value.vacationDays) || 0
  const total = parseFloat(totalLeaveDays.value) || 0
  const remaining = available - total

  if (remaining < 0) {
    ElMessage.error(`调休天数不足，请重新调整调休天数`)
    return
  }

  // 提交数据
  const submitData = {
    vacationApplications: vacationData.value.map(row => ({
      attendanceCycle: row.attendancePeriod,
      applicationDate: formData.value.applicationDate,
      vacationDate: row.leaveDate,
      vacationType: '调休',
      vacationPeriod: row.leavePeriod,
      reason: textarea.value
    }))
  }

  console.log(submitData.vacationApplications)

  // 调用API提交
  request({
    url: "/vacationApplication/insert",
    method: "post",
    data: submitData.vacationApplications
  }).then(res => {
    if (res.code === 200) {
      request({
        url: "/vacationBalance/update",
        method: "post",
        params: {
          totalLeaveDays: parseFloat(totalLeaveDays.value).toFixed(2)
        }
      }).then(resp => {
        if (resp.code === 200) {
          emits('ref-table')
        } else {
          ElMessage.error(resp.msg)
        }
      })
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 设置当前日期
const setCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  formData.value.applicationDate = `${year}-${month}-${day}`;
}

// 组件挂载时设置当前日期
onMounted(() => {
  setCurrentDate();
  calculateTotalLeaveDays();
  loadVacationBalance();
})

// 监听调休数据变化，自动计算总天数
watch(vacationData, () => {
  calculateTotalLeaveDays()
}, { deep: true })

// 监听可用天数变化
watch(() => vacationBalanceData.value.vacationDays, () => {
  calculateRemainingDays()
})

// 监听总天数变化
watch(totalLeaveDays, () => {
  calculateRemainingDays()
})
</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
  height: 6px;
  background-color: #ccebf7;
  border-radius: 3px;
  display: flex;
  width: 100%;
  /* 确保进度条容器宽度占满父容器 */
  overflow: hidden;
  /* 防止子元素溢出 */
}

.progress {
  width: 8%;
  height: 10;
  background-color: #61c3ea;
  border-radius: 3px 0 0 3px;
  transition: width 0.3s ease;
  /* 添加宽度变化的过渡效果 */
}

.bottom-submit-bar {
  /* position: fixed; */
  /* 固定定位 */
  bottom: 0;
  /* 靠底部 */
  left: 0;
  width: 100%;
  background-color: #fff;
  /* 背景色，可根据需求调整 */
  border-top: 1px solid #eaeaea;
  /* 顶部边框，与页面区分 */
  padding: 12px 24px;
  /* 内边距，适配截图里的间距风格 */
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /* 按钮靠左，可根据实际需求调整 */
  z-index: 10;
  /* 提高层级，避免被其他内容覆盖 */
}
</style>